/*
 * @Author: wangyongcun
 * @Date: 2023-09-06 10:50:08
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-06-10 20:53:59
 * @Description: 文件管理
 * @link: COS文档 https://cloud.tencent.com/document/product/436/8629
 */
import fs from "fs";
import COS from "cos-nodejs-sdk-v5";
const { secretId, secretKey, bucket, region, prefix } = globalConfig.cosConfig;
const cos = new COS({
  SecretId: secretId,
  SecretKey: secretKey,
});

class File {
  constructor() {}
  /**
   * @description: 上传文件
   * @param {*} ctx
   * @return {*}
   */
  async uploadFile(ctx) {
    try {
      const file = ctx.request.files?.file; // 获取上传的文件
      // 获取参数
      if (!file || file.size <= 0) throw "请上传文件";
      // 上传文件
      const { newFilename, filepath } = file;
      const key = `${prefix || ""}${newFilename}`;
      const res = await cos.putObject({
        Bucket: bucket,
        Region: region,
        Key: key,
        Body: fs.createReadStream(filepath),
      });
      // 返回结果
      ctx.body = resUtil.success({
        Message: "上传成功",
        Key: key,
      });
    } catch (err) {
      log.error(`File-uploadFile-上传文件失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 下载文件
   * @param {*} ctx
   * @return {*}
   */
  async downloadFile(ctx) {
    try {
      let key = ctx.query.key || ctx.request.body.key;
      // 获取参数
      if (!key) {
        ctx.body = resUtil.error(`key参数不能为空！`);
        return;
      }
      let res = await cos.getObject({
        Bucket: bucket,
        Region: region,
        Key: key,
      });
      // 返回结果
      ctx.set("Content-Type", res.headers["content-Type"]);
      ctx.body = res.Body;
    } catch (err) {
      log.error(`File-downloadFile-下载失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 删除文件
   * @param {*} ctx
   * @return {*}
   */
  async deleteFile(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["key"], ctx);
      if (isEmpty) return;
      let key = ctx.request.body.key;
      // 添加到数据库
      let res = await cos.deleteObject({
        Bucket: bucket,
        Region: region,
        Key: key,
      });
      // 返回结果
      ctx.body = resUtil.success("删除成功");
    } catch (err) {
      log.error(`File-deleteFile-删除失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
}

export default new File();
